
using com.tc.config;

using com.tc.serial;

using com.tc.zigbee.entity;

using com.tc.zigbee.mt;

using com.tc.zigbee.mt.request;
using com.tc.gateway.tunnel;
using System;
using com.tc.zigbee.zcl;
using com.tc.gateway.serial;
namespace com.tc.assistance.home
{
    public class HomeApplication : ErrorListener
    {
        public ZigbeeManager getManager()
        {
            return manager;
        }

        public HomeApplication()
        {

        }

        Monitor monitor;
        ZigbeeManager manager;
        TunnelServer tunnelServer;
        bool started = false;
        public TunnelServer getTunnelServer()
        {
            return tunnelServer;
        }
        SerialStream stream;
        public void start()
        {
            stream = SerialFactory.getStream();
            if (stream == null)
                throw new Exception();
            if (WorkingConfig.mainController)
                tunnelServer = TunnelManager.getServer(stream.getOutputStream());
            monitor = new Monitor(stream, tunnelServer);
            manager = new ZigbeeManager();
            if (WorkingConfig.simulator)
                manager.createDummy();

            monitor.addListener(manager);

            monitor.setErrorListener(this);
            monitor.start();
            Endpoint ep = manager.getRemoteControl();
            MtCommand r = RequestFactory.MtAfRegister(ep);
            RequestQueue.offer(r);
            r = RequestFactory.MtIEEEAddrRequest((short)0x00, (byte)0, (byte)1);
            RequestQueue.offer(r);
            started = true;


        }

        public bool isStarted()
        {
            return started;
        }

        public void stop()
        {
            monitor = null;
            manager = null;
            if (tunnelServer != null)
            {
                tunnelServer.stop();
                tunnelServer = null;
            }

            started = false;
        }
        public void onException(Exception e)
        {
            stop();


        }
    }
}